/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkalex.htdi.base;

import java.io.IOException;
import java.util.logging.*;
import javax.annotation.Resource;
import org.redkale.convert.json.JsonConvert;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.util.AnyValue;
import org.redkalex.htdi.user.*;

/**
 *
 * @author zhangjx
 */
@HttpUserType(UserInfo.class)
public class BaseServlet extends HttpServlet {

    protected final Logger logger = Logger.getLogger(this.getClass().getSimpleName());

    protected static final RetResult RET_UNLOGIN = RetCodes.retResult(RetCodes.RET_USER_UNLOGIN);

    protected static final RetResult RET_AUTHILLEGAL = RetCodes.retResult(RetCodes.RET_USER_AUTH_ILLEGAL);

    @Resource
    protected JsonConvert convert;

    @Resource
    private UserService service;

    @Override
    public void init(HttpContext context, AnyValue config) {
        super.init(context, config);
    }

    /**
     * Servlet的入口判断，一般用于全局的基本校验和预处理
     *
     * @param request  HTTP请求对象
     * @param response HTTP响应对象
     *
     * @throws IOException
     */
    @Override
    public void preExecute(final HttpRequest request, final HttpResponse response) throws IOException {
        request.setCurrentUser(currentUser(service, request));
        response.nextEvent();
    }

    /**
     * 校验用户的登录态
     *
     * @param request  HTTP请求对象
     * @param response HTTP响应对象
     *
     * @throws IOException
     */
    @Override
    public final void authenticate(HttpRequest request, HttpResponse response) throws IOException {
        UserInfo info = request.currentUser();
        if (info == null) {
            response.finish(403, "未登录"); //未登录
            return;
        } else if (!info.checkAuth(request.getModuleid(), request.getActionid())) {
            response.finish(RET_AUTHILLEGAL);  //鉴权失败
            return;
        }
        response.nextEvent();
    }

    /**
     * 获取当前用户对象，没有返回null
     *
     * @param service UserService
     * @param req     HTTP请求对象
     *
     * @return
     * @throws IOException
     */
    public static final UserInfo currentUser(UserService service, HttpRequest req) throws IOException {
        UserInfo user = (UserInfo) req.currentUser();
        return user != null ? user : service.current(req.getSessionid(false));
    }

}
